package com.janal.controller.Login_Register;

import com.janal.model.admin.Admin;
import com.janal.service.login.AdminLoginServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author Lenovo
 */
public class AdminLoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从前端获取管理源的账号密码
        String adminCode = req.getParameter("adminCode");
        String adminPassword = req.getParameter("adminPassword");
        Admin getadmin = new Admin(adminCode,adminPassword);

        //调用service进行用户匹配
        AdminLoginServiceImpl alsi = new AdminLoginServiceImpl();
        Admin resultAdmin = alsi.adminLogin(getadmin);

        if (resultAdmin == null) {
            req.setAttribute("AdminLoginError", "该管理员账户不存在");
            req.getRequestDispatcher("AdminLogin.jsp").forward(req, resp);
        } else if (resultAdmin.getAdminPassword() == null) {
            req.setAttribute("AdminLoginError", "管理员密码错误！");
            req.getRequestDispatcher("AdminLogin.jsp").forward(req, resp);
        } else {      //登录成功
            HttpSession session = req.getSession();
            session.setAttribute("adminCode",adminCode);
            session.setAttribute("adminPassword",adminPassword);
            session.setAttribute("resultAdmin", resultAdmin);
            resp.sendRedirect("/p/adminHome.html");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
